<template>
  <div
    class="carousel"
    :style="{'background-color':bgColor}"
    v-if="show"
  >
    <div class="carousel-left">
      <img
        src="../assets/carousel-notice-btn.png"
        alt=""
      >
    </div>
    <div
      class="carousel-content"
      ref="content"
    >
      <p
        :style="{color: color,transform: 'translate3d('+textLeft+'px,0,0)'}"
        ref="text"
      >{{text}}</p>
    </div>
    <div
      class="carousel-right"
      @click="show=false"
    >
      <img
        src="../assets/carousel-close-btn.png"
        alt=""
      >
    </div>
  </div>
</template>

<script>
let timer
let contentWidth = 0
let textWidth = 0
export default {
  props: {
    text: { // 滚动文字的内容
      type: String,
      default: ''
    },
    bgColor: { // 整个走马灯背景颜色
      type: String,
      default: '#fff'
    },
    color: { // 滚动文字的颜色
      type: String,
      default: '#fff'
    },
    speed: { // 走马灯移动的速度
      type: Number,
      default: 1
    },
    interval: { // interval时间间隔
      type: Number,
      default: 30
    }
  },
  data() {
    return {
      textLeft: 0,
      show: true
    }
  },
  mounted() {
    contentWidth = this.$refs.content.offsetWidth
    textWidth = this.$refs.text.offsetWidth
    this.textLeft = contentWidth
    this.startToMove()
  },
  destroyed() {
    if (timer) {
      clearInterval(timer)
    }
  },
  methods: {
    startToMove() {
      timer = setInterval(() => {
        this.textLeft -= this.speed
        if (this.textLeft < -1 * textWidth) {
          this.textLeft = contentWidth
        }
      }, this.interval)
    }
  }
}
</script>

<style scoped lang="scss">
.carousel {
  width: 100%;
  height: 0.86rem;
  line-height: 0.86rem;
  display: flex;
  .carousel-left,
  .carousel-right {
    width: 0.7rem;
    padding: 0 0.2rem;
    text-align: center;
    img {
      display: inline-block;
      vertical-align: middle;
    }
  }
  .carousel-left img {
    width: 0.32rem;
    height: auto;
  }
  .carousel-right img {
    width: 0.27rem;
    height: auto;
  }
  .carousel-content {
    flex-grow: 1;
    overflow: hidden;
    p {
      display: inline-block;
      font-size: 0.28rem;
      font-weight: 700;
      vertical-align: middle;
    }
  }
}
</style>
